<template>
  <div class="followup-plan">
    <!-- 搜索区域 -->
    <div class="search-bar">
      <el-input v-model="name" placeholder="请输入计划名称" style="width: 300px" />
      <el-button type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
    </div>

    <!-- 随访计划列表 -->
    <div class="plan-list">
      <h3 class="selected-plan">
        <el-form-item label="已选随访计划：" prop="startDate">
          <h3 class="selected-plan" style="margin: 0">{{ selectedPlan?.name || '无' }}</h3>
        </el-form-item>
      </h3>
      <h3 class="selected-plan">
        <el-form-item label="计划执行日期：" prop="planDate">
          <el-date-picker
            v-model="form.planDate"
            type="date"
            placeholder="选择计划执行日期"
            value-format="YYYY-MM-DD"
            :disabled-date="disableBeforeToday"
          />
        </el-form-item>
      </h3>

      <el-table :data="plans" border align="center">
        <el-table-column prop="name" label="计划名称" />
        <el-table-column prop="description" label="描述">
          <template #default="{ row }">
            <span class="plan-desc">{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button text type="primary" @click="selectPlan(2, row)"> 预 览 </el-button>
            <el-button
              text
              @click="selectPlan(1, row)"
              :class="{ selected: selectedPlan?.id === row.id }"
            >
              {{ selectedPlan?.id === row.id ? '已选择' : '选择' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="plansPage.current"
          v-model:page-size="plansPage.pageSize"
          :size="size"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="plansPage.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 添加预约按钮 -->
    <div class="add-btn">
      <el-button type="primary" @click="handleSubmit">{{
        menuVal.type === 1 ? '修改预约' : '添加预约'
      }}</el-button>
    </div>

    <!-- 预约记录 -->
    <div class="appointment-records">
      <h3>预约记录</h3>
      <el-table :data="tableData" empty-text="没有找到匹配的记录">
        <el-table-column prop="visitDate" label="随访时间" />
        <el-table-column prop="notice" label="是否通知">
          <template #default="scope">
            <span>{{ ['否', '是'][Number(scope.row.notice)] }}</span>
          </template>
        </el-table-column>
<!--        <el-table-column prop="noticeType" label="通知方式">
          <template #default="scope">
            <span v-for="(item, index) in scope.row.noticeType.split(',')" :key="index"
              >{{ ['短信', '邮件'][Number(item) - 1] }}
              <span v-if="index + 1 != scope.row.noticeType.split(',').length">|</span>
            </span>
          </template>
        </el-table-column>-->
        <el-table-column prop="noticeTime" label="通知时间">
          <template #default="scope">
            <span v-for="(item, index) in scope.row.noticeTime.split(',')" :key="index"
              >{{ ['提前一周通知', '提前三天通知', '当天通知'][Number(item) - 1] }}
              <span v-if="index + 1 != scope.row.noticeTime.split(',').length">|</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="noticeContent" label="通知内容" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            {{ ['已预约', '已发送'][Number(scope.row.status) - 1] }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="text" @click="handleMenu(1, scope.row, scope.$index)">修 改</el-button>
            <el-button type="text" @click="handleMenu(2, scope.row, scope.$index)">取 消</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="tablePlansPage.current"
          v-model:page-size="tablePlansPage.pageSize"
          :size="size"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="tablePlansPage.total"
          @size-change="handleSizeChangeItem"
          @current-change="handleCurrentChangeItem"
        />
      </div>
    </div>
    <visitPlanItem ref="visitplanitemRef" />
  </div>
</template>

<script setup>
import { getList } from '@/api/followupvisitplan/followUpVisitPlan';
import visitPlanItem from '@/views/followupvisitplan/components/visitPlanItem.vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  getLists,
  getDetail,
  add,
  update,
  remove,
  submitWithPlan,
} from '@/api/visitplanrecord/visitPlanRecord';
import { ref, reactive, computed } from 'vue';

import { useRoute } from 'vue-router';
import { useStore } from 'vuex';
const store = useStore();
const route = useRoute();
const routerQuery = ref({});
routerQuery.value = route.query;

const activeTab = ref('随访计划');
const name = ref('');
const selectedPlan = ref(null);
const form = ref({
  planDate: '',
});
// 随访计划数据
const plans = ref([]);
let plansPage = ref({
  current: 1,
  pageSize: 10,
  total: 0,
});

let tablePlansPage = ref({
  current: 1,
  pageSize: 10,
  total: 0,
});

let tableData = ref([]);

let visitplanitemRef = ref(null);

// 过滤后的计划列表
// const filteredPlans = computed(() => {
//   return plans.filter(plan => plan.name.toLowerCase().includes(searchQuery.value.toLowerCase()));
// });
let menuVal = ref({
  type: null,
  row: {},
  index: null,
});

const props = defineProps({
  appointmentData: {
    type: Object,
    default: {},
  }
});
/*
  type 1:修改
  type 2:取消
*/
const handleMenu = (type, row = {}, index = null) => {
  let val = JSON.parse(JSON.stringify(row));
  menuVal.value.type = type;
  menuVal.value.row = row;
  menuVal.value.index = index;
  if (type === 1) {
    val.noticeTime = val.noticeTime.split(',');
    val.noticeType = val.noticeType.split(',');
    form.value = val;
  }
  if (type === 2) {
    ElMessageBox.confirm(`确认取消${row.visitDate}随访吗`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        return remove(row.id);
      })
      .then(() => {
        initTableData(tablePlansPage.value);
        ElMessage.success('操作成功!');
      });
  }
};

const handleSubmit = () => {
  if (!form.value.planDate) {
    ElMessage.error('请选择正确的日期');
    return;
  }
  console.log(selectedPlan.value);
  if (selectedPlan.value == null) {
    ElMessage.error('请选择计划');
    return;
  }
  form.value.trial = routerQuery.value.trialId;
  submitWithPlan(
    form.value.planDate,
    selectedPlan.value.id,
    props.appointmentData.id,
    form.value.trial
  ).then(res => {
    ElMessage({
      type: 'success',
      message: '操作成功!',
    });
    form.value.planDate = null;
    selectedPlan.value = null;
    // emit('cutChange', '单次预约');
    initTableData(plansPage.value);
  });
};

// 表格接口
const initTableData = (page, params = {}) => {
  let values = {
    descs: 'create_time',
    ...params,
    caseUserId: props.appointmentData.id,
    trial: routerQuery.value.trialId,
  };
  getLists(page.current, page.pageSize, values).then(res => {
    const DATA = res.data.data;
    tablePlansPage.value.total = DATA.total;
    tableData.value = DATA.records;
  });
};

/*
  type 1:选择
  type 2:预览
*/
const selectPlan = (type, plan) => {
  const actions = {
    1: () => {
      selectedPlan.value = selectedPlan.value?.id === plan.id ? null : plan;
    },
    2: () => {
      visitplanitemRef.value.open(plan);
    },
  };

  // 执行对应的操作
  if (actions[type]) actions[type]();
};
// 查询按钮点击事件
const handleSearch = () => {
  let params = {
    name: name.value,
  };
  plansGeiList(plansPage.value, params);
};


const handleCurrentChangeItem  = currentPage => {
  tablePlansPage.value.currentPage = currentPage;
  initTableData(tablePlansPage.value);
};
const handleSizeChangeItem = pageSize => {
  tablePlansPage.value.pageSize = pageSize;
  initTableData(tablePlansPage.value);
};



const handleCurrentChange = currentPage => {
  plansPage.value.currentPage = currentPage;
  plansGeiList(plansPage.value);
};
const handleSizeChange = pageSize => {
  plansPage.value.pageSize = pageSize;
  plansGeiList(plansPage.value);
};
const plansGeiList = (page, params = {}) => {
  let values = {
    descs: 'create_time',
    ...params,
  };

  getList(page.current, page.pageSize, values).then(res => {
    const DATA = res.data.data;
    plansPage.value.total = DATA.total;
    plans.value = DATA.records;
  });
};
// 禁用今天之前的日期
const disableBeforeToday = date => {
  const today = new Date();
  today.setHours(0, 0, 0, 0); // 设置为今天的00:00:00，避免时间比较问题
  return date < today; // 如果日期小于今天，则禁用
};
onMounted(() => {
  plansGeiList(plansPage.value);
  initTableData(plansPage.value);
});
</script>

<style scoped lang="scss">
.followup-plan {
  padding: 20px;
  background: white;
}

.type-tabs {
  margin-bottom: 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.plan-list {
  .selected-plan {
    color: #666;
    margin: 15px 0;
    font-weight: normal;
  }

  .plan-desc {
    color: #999;
    font-size: 14px;
  }

  .selected {
    color: #409eff;
    font-weight: bold;
  }
}

.pagination {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
  align-items: center;

  .info {
    color: #666;
    font-size: 12px;
  }
}

.add-btn {
  margin: 20px 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.appointment-records {
  border-top: 1px solid #ebeef5;
  padding-top: 20px;
}

:deep(.el-table) {
  margin-top: 15px;

  th {
    background-color: #f5f7fa;
  }

  .cell {
    padding: 0 8px;
  }
}
</style>
